//
//  XSQGController.m
//  N9Mi
//
//  Created by Sunshine on 2018/7/20.
//  Copyright © 2018年 Sunshine. All rights reserved.
//

#import "XSQGController.h"
#import "XSHeaderView.h"
#import "ShopDetailController.h"
#import "TimerView.h"
@interface XSQGController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)XSHeaderView *headerView;
@property(nonatomic,strong)UITableView *listTableview;
@property(nonatomic,strong)NSArray *contentArray;
@property(nonatomic,strong)UILabel *timelab;
@property(nonatomic,strong)TimerView *timeview;
@property(nonatomic,assign)NSInteger timeNum;
@property(nonatomic,strong)NSTimer *mytimer;
@end

@implementation XSQGController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatDataMethod];
    [self creatHeaderViewMethod];
    [self createTableviewMethod];
    NSDictionary *onedic = self.datasource[0];
    self.timeNum = [onedic[@"COUNTDOWN"] integerValue];
    self.mytimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timingSendAction) userInfo:nil repeats:YES];
}






-(void)creatDataMethod{
    NSDictionary *onedic = self.datasource[0];
    NSString *urlstr = [NSString stringWithFormat:@"/dashop/seckillgoods/app/getSecKillGoods.do?SECKILL_ID=%@",onedic[@"SECKILL_ID"]];
    NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:urlstr];
    [self ContentDataMethodWithUrl:endstr];
}
-(void)createTableviewMethod{
    self.listTableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 52*kJLXWidthScale, kScreenWidth, kScreenHeight - 52*kJLXWidthScale) style:UITableViewStylePlain];
    [self.view addSubview:self.listTableview];
    if (kScreenHeight == 812) {
        self.listTableview.sd_layout
        .bottomSpaceToView(self.view, 34);
    }
    self.listTableview.dataSource = self;
    self.listTableview.delegate = self;
    [self.listTableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"onecell"];
    //分隔线
    self.listTableview.separatorStyle = UITableViewCellAccessoryNone;
    //去掉尾部多余的空白
    [self.listTableview setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    
    UIView *headerview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 95*kJLXWidthScale)];
    headerview.backgroundColor = [UIColor whiteColor];
    UILabel *timelab = [UILabel new];
    self.timelab = timelab;
    
    timelab.backgroundColor = [UIColor redColor];
    timelab.layer.masksToBounds = YES;
    timelab.layer.cornerRadius = 5*kJLXWidthScale;
    timelab.numberOfLines = 2;
    timelab.textAlignment = NSTextAlignmentCenter;
    [headerview addSubview:timelab];
    timelab.sd_layout
    .topSpaceToView(headerview, 8*kJLXWidthScale)
    .centerXEqualToView(headerview)
    .heightIs(45*kJLXWidthScale)
    .widthIs(180*kJLXWidthScale);
    
     NSDictionary *onedic = self.datasource[0];
    NSString *str = [NSString stringWithFormat:@"抢购中"];
    NSString*string =[NSString stringWithFormat:@"%@ - %@\n%@",onedic[@"START_TIME"],onedic[@"END_TIME"],str];
    NSRange range = [string rangeOfString: str];
    NSMutableAttributedString*attribute = [[NSMutableAttributedString alloc] initWithString: string];
    [attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:18*kJLXWidthScale]}range: NSMakeRange(0, range.location)];
    [attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:13*kJLXWidthScale]}range: range];
    [timelab setText: string];
    [timelab setAttributedText: attribute];
    
    UILabel *linelab = [UILabel new];
    linelab.backgroundColor = LineColor;
    [headerview addSubview:linelab];
    linelab.sd_layout
    .bottomSpaceToView(headerview, 0)
    .leftSpaceToView(headerview, 0)
    .rightSpaceToView(headerview, 0)
    .heightIs(1);
    
    UILabel *leflab = [UILabel new];
    leflab.textColor = [UIColor darkGrayColor];
    leflab.text = @"限时抢购，先到先得";
    leflab.font = [UIFont systemFontOfSize:13*kJLXWidthScale];
    [headerview addSubview:leflab];
    leflab.sd_layout
    .bottomSpaceToView(headerview, 5*kJLXWidthScale)
    .leftSpaceToView(headerview, 8*kJLXWidthScale)
    .heightIs(20*kJLXWidthScale)
    .widthIs(120*kJLXWidthScale);
    
    self.timeview = [[TimerView alloc]initWithFrame:CGRectMake(kScreenWidth - 110*kJLXWidthScale, headerview.height - 30, 100*kJLXWidthScale, 20*kJLXWidthScale)];
    [headerview addSubview:self.timeview];
    
    UILabel *lab = [UILabel new];
    lab.text = [NSString stringWithFormat:@"距结束："];
    lab.font = [UIFont systemFontOfSize:13*kJLXWidthScale];
    [headerview addSubview:lab];
    lab.sd_layout
    .centerYEqualToView(leflab)
    .rightSpaceToView(self.timeview, 0)
    .leftSpaceToView(leflab, 5*kJLXWidthScale)
    .heightIs(20*kJLXWidthScale);
    self.listTableview.tableHeaderView = headerview;
    
}
- (void)getDetailTimeWithTimestamp:(NSInteger)timestamp {
    
    
    NSInteger ms = timestamp;
    NSInteger ss = 1;
    NSInteger mi = ss * 60;
    NSInteger hh = mi * 60;
    
    NSInteger dd = hh * 24;
    NSInteger day = ms / dd;// 天
    NSInteger hour = (ms - day * dd) / hh;// 时
    NSInteger minute = (ms - day * dd - hour * hh) / mi;// 分
    NSInteger second = (ms - day * dd - hour * hh - minute * mi) / ss;// 秒
    self.timeview.hourlab.text = [NSString stringWithFormat:@"%02ld",(long)hour];
    self.timeview.minlab.text = [NSString stringWithFormat:@"%02ld",minute];
    self.timeview.sslab.text = [NSString stringWithFormat:@"%02ld",second];
}
    
    



-(void)creatHeaderViewMethod{
    self.headerView = [[XSHeaderView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth, 52*kJLXWidthScale)];
    self.headerView.backgroundColor = LineBackColor;
    self.headerView.dataArray = self.datasource;
    __weak typeof(self)weakself = self;
    self.headerView.headerBlock = ^(NSDictionary *hdic,NSInteger index) {
        [weakself.mytimer invalidate];
        weakself.mytimer = nil;
        weakself.timeNum = [hdic[@"COUNTDOWN"] integerValue];
        weakself.mytimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:weakself selector:@selector(timingSendAction) userInfo:nil repeats:YES];
        NSString *urlstr = [NSString stringWithFormat:@"/dashop/seckillgoods/app/getSecKillGoods.do?SECKILL_ID=%@",hdic[@"SECKILL_ID"]];
        NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:urlstr];
        [weakself ContentDataMethodWithUrl:endstr];
        
    };
    [self.view addSubview:self.headerView];
}
-(void)timingSendAction{
    
    if (self.timeNum <= 0) {
        [self.mytimer invalidate];
        self.mytimer = nil;
    }else{
        self.timeNum --;
        [self getDetailTimeWithTimestamp:self.timeNum];
    }
}
//限时抢购按钮图
-(void)ContentDataMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        self.contentArray = response;
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            [self.listTableview reloadData];
        }];
    } failBlock:^(NSError *error) {
        
    }];
    
}

- (void)verificationCode:(long long)time blockYes:(void(^)(void))blockYes blockNo:(void(^)(id time))blockNo
{
    __block long long timeout = time; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){
            //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                blockYes();
            });
        }else{
            NSString *strTime = [NSString stringWithFormat:@"%lld",timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                blockNo(strTime);
            });
            timeout--;
        }
        
        
    });
    dispatch_resume(_timer);
    
    
}

#pragma mark --UITableViewDelegate,UITableViewDataSource--


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.contentArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"onecell" forIndexPath:indexPath];
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *dic = self.contentArray[indexPath.row];
    UIView *backview = [UIView new];
    backview.layer.masksToBounds = YES;
    backview.layer.cornerRadius = 5*kJLXWidthScale;
    backview.layer.borderColor = LineBackColor.CGColor;
    backview.layer.borderWidth = 1;
    [cell.contentView addSubview:backview];
    backview.sd_layout
    .topSpaceToView(cell.contentView, 8*kJLXWidthScale)
    .leftSpaceToView(cell.contentView, 8*kJLXWidthScale)
    .rightSpaceToView(cell.contentView, 8*kJLXWidthScale)
    .bottomSpaceToView(cell.contentView, 8*kJLXWidthScale);
    
    UIImageView *imagevi = [UIImageView new];
    NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:dic[@"GOODS_PIC"]];
    [imagevi sd_setImageWithURL:[NSURL URLWithString:endstr]];
    [backview addSubview:imagevi];
    imagevi.sd_layout
    .topSpaceToView(backview, 8*kJLXWidthScale)
    .leftSpaceToView(backview, 10*kJLXWidthScale)
    .bottomSpaceToView(backview, 8*kJLXWidthScale)
    .widthIs(80*kJLXWidthScale);
    
    UILabel *titlab = [UILabel new];
    titlab.text = [NSString stringWithFormat:@"%@",dic[@"GOODS_NAME"]];
    titlab.font = [UIFont systemFontOfSize:18*kJLXWidthScale];
    titlab.textColor = [UIColor darkGrayColor];
    [backview addSubview:titlab];
    titlab.sd_layout
    .topSpaceToView(backview, 8*kJLXWidthScale)
    .leftSpaceToView(imagevi, 5*kJLXWidthScale)
    .rightSpaceToView(backview, 8*kJLXWidthScale)
    .heightIs(30*kJLXWidthScale);
    
    UILabel *sumlab = [UILabel new];
    sumlab.text = [NSString stringWithFormat:@"秒杀数量：%@",dic[@"GOODS_NUM"]];
    sumlab.font = [UIFont systemFontOfSize:13*kJLXWidthScale];
    sumlab.textColor = LineColor;
    [backview addSubview:sumlab];
    sumlab.sd_layout
    .bottomSpaceToView(backview, 8*kJLXWidthScale)
    .leftSpaceToView(imagevi, 5*kJLXWidthScale)
    .rightSpaceToView(backview, 120*kJLXWidthScale)
    .heightIs(20*kJLXWidthScale);
    
    
    
    
    UILabel *pricelab = [UILabel new];
    pricelab.textColor = [UIColor darkGrayColor];
    [backview addSubview:pricelab];
    pricelab.sd_layout
    .bottomSpaceToView(sumlab, 0)
    .leftSpaceToView(imagevi, 5*kJLXWidthScale)
    .rightSpaceToView(backview, 120*kJLXWidthScale)
    .heightIs(30*kJLXWidthScale);
    
    NSString *str = [NSString stringWithFormat:@"￥%.2f",[dic[@"GOODS_MARKETPRICE"] floatValue]];
    NSString*string =[NSString stringWithFormat:@"￥%.1f %@",[dic[@"GOODS_PRICE"] floatValue],str];
    NSRange range = [string rangeOfString: str];
    NSMutableAttributedString*attribute = [[NSMutableAttributedString alloc] initWithString: string];
    [attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor orangeColor],NSFontAttributeName:[UIFont systemFontOfSize:16*kJLXWidthScale]}range: NSMakeRange(0, range.location)];
    [attribute addAttributes: @{NSForegroundColorAttributeName: LineColor,NSFontAttributeName:[UIFont systemFontOfSize:13*kJLXWidthScale]}range: range];
    //设置格式下划线还是删除线
    [attribute addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:range];
    [pricelab setText: string];
    [pricelab setAttributedText: attribute];
    
    MineButton *btn = [MineButton buttonWithType:UIButtonTypeCustom];
    btn.usinfo = dic;
    btn.titleLabel.font = [UIFont systemFontOfSize:20*kJLXWidthScale];
    btn.backgroundColor = [UIColor redColor];
    [btn setTitle:@"马上抢" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(qiangGouButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [backview addSubview:btn];
    btn.sd_layout
    .bottomSpaceToView(backview, 8*kJLXWidthScale)
    .rightSpaceToView(backview, 8*kJLXWidthScale)
    .heightIs(35*kJLXWidthScale)
    .widthIs(80*kJLXWidthScale);
    
    return cell;
    
}

-(void)qiangGouButtonAction:(MineButton *)sender{
    ShopDetailController *devc = [[ShopDetailController alloc]init];
    NSString *urlstr = [NSString stringWithFormat:@"/dashop/goods/app/getGoods?GOODS_ID=%@",sender.usinfo[@"GOODS_ID"]];
    devc.urlStr = urlstr;
    devc.usdic = sender.usinfo;
    [self.navigationController pushViewController:devc animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 120*kJLXWidthScale;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}
   



@end
